<script setup>
import axios from '@/util/axios'
import { ElMessage } from "element-plus"
import { onMounted, ref } from "vue"

const formRef = ref(null)
const form = ref({
  userName: '',
  password: '',
  oldPassword: '',
  newPassword: '',
  newPassword2: ''
})
const initFormData = () => {
  const userInfoJson = window.sessionStorage.getItem("userInfo")
  form.value = JSON.parse(userInfoJson)
}
onMounted(() => {
  initFormData()
})
const validatePassword = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请再次输入密码'))
  } else if(value != form.value.newPassword) {
    callback(new Error('请确保两次输入的密码一致'))
  } else {
    callback()
  }
}
const rules = ref({
  userName: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
  ],
   oldPassword: [
    { required: true, message: '请输入原密码', trigger: 'blur' },
  ],
   newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
  ],
   newPassword2: [
    { validator: validatePassword, trigger: 'blur' },
  ]
})

import { useStore } from 'vuex'
const store = useStore()
const logout = () => {
  store.dispatch('logout')
}
const onSubmit = () => {
  formRef.value.validate(async(valid) => {
    if(valid) {
      if (form.value.oldPassword !== form.value.password) {
        ElMessage.error("原密码错误")
      } else {
        try {
          const result = await axios.post('admin/modifyPassword', form.value)
          const data = result.data
          if (data.code == 0) {
            ElMessage.success("密码修改成功，请重新登录")
            formRef.value.resetFields()
            logout()
          } else {
            ElMessage.error(data.msg)
          }
        } catch (error) {
          ElMessage.error("系统运行出错，请联系管理员")
        }
      }
    } else {
      console.log("fail")
    }
  })
}

</script>

<template>
  <el-card>
    <el-form
    ref="formRef"
    :model="form"
    :rules="rules"
    label-width="150px"
    >
      <el-form-item label="用户名" prop="userName">
        <el-input v-model="form.userName" disabled />
      </el-form-item>
      <el-form-item label="原密码" prop="oldPassword">
        <el-input v-model="form.oldPassword" type="password" />
      </el-form-item>
      <el-form-item label="新密码" prop="newPassword">
        <el-input v-model="form.newPassword" type="password" />
      </el-form-item>
      <el-form-item label="确认新密码" prop="newPassword2">
        <el-input v-model="form.newPassword2" type="password" />
      </el-form-item>
      
      <el-form-item>
        <el-button type="primary" @click="onSubmit">确认修改</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<style scoped lang="scss">
  .el-input{
    width: 300px;
  }
</style>
